
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Xml;
using System.Xml.XPath;

namespace BiteTheBullet.DNN.Utils
{

	public class RssReader
	{
		private string _response;
		private int _timeout = 3000;
		private bool _connected = false;
		private HttpWebRequest _webRequest;
		public RssReader(string url):this(url, "", "", "")
		{

		}

		public RssReader(string url, string proxyHost, string proxyUsername, string proxyPassword)
		{
			_webRequest = (HttpWebRequest)WebRequest.Create(url);

			if(proxyHost != null && proxyHost != string.Empty)
			{
        try
        {
          _webRequest.Proxy = new WebProxy(proxyHost);
				}
				catch(Exception)
				{
				}
      }
			if(proxyUsername != null && proxyUsername != string.Empty)
			{
				_webRequest.Proxy.Credentials = new NetworkCredential(proxyUsername, proxyPassword);
			}
		}
		public int TimeOut
		{
			get{ return _timeout;}
			set{ _timeout = value;}
		}
		public string Response()
		{
			if(!_connected)
				this.Connect();

			return _response;
		}

		public int Ttl()
		{
			string ttl = this.GetElement("/rss/channel/ttl");
			if(ttl != null)
				return Int32.Parse(ttl);
			else
				return -1;			
		}

		public string LocationName()
		{
			string location = this.GetElement("/rss/channel/title");

			//filter off the yahoo 
			return location.Substring(location.IndexOf("-") + 2);
		}

		public string GetElement(string XpathQuery)
		{
			ArrayList list = this.GetElements(XpathQuery);
			if(list.Count > 0)
			{
				//just peel off the first item
				return list[0].ToString();
			}else
				return null;
		}

		public ArrayList GetElements(string XpathQuery)
		{
			if(!_connected)
				this.Connect();

			
			XmlTextReader reader = new XmlTextReader(_response, XmlNodeType.Document, null);
			XPathDocument doc = new XPathDocument(reader);
			XPathNavigator query = doc.CreateNavigator();
			XPathNodeIterator iterator = query.Select(XpathQuery);

			ArrayList elements = new ArrayList();

			while(iterator.MoveNext())
			{
				elements.Add(iterator.Current.Value);
			}

			reader.Close();
			return elements;
			
		}

		/// <summary>
		/// Connects to the remote Url and stores the response
		/// </summary>
		private void Connect()
		{
			_webRequest.Timeout = _timeout;
			WebResponse response = _webRequest.GetResponse();
			
			Stream input = response.GetResponseStream();
			StreamReader reader = new StreamReader(input);
			_response = reader.ReadToEnd();
			_connected = true;
		}
	}
}
